<template>
  <div class="apaasApiConfigPage">
    <el-card class="box-card">
      <div class="baseInfoArea">
        <div class="config-base-box base">
          <div class="config-title"><i class="el-icon-vertical-bar"></i>基础信息</div>
          <div class="config-content">
            <avue-form ref="apiForm" v-model="apiInfo" :option="apiInfoOption"> </avue-form>
          </div>
        </div>
        <div class="config-base-box base">
          <div class="config-title"><i class="el-icon-vertical-bar"></i>参数信息配置</div>
          <div class="config-contents">
            <avue-crud :data="paramsData" :option="paramsOption" @row-del="paramsRowDel">
              <template slot-scope="scope" slot="menuLeft">
                <el-button type="primary" icon="el-icon-plus" size="small" @click="openCommonParamsModal()">新增参数</el-button>
              </template>
            </avue-crud>
          </div>
        </div>
        <div class="config-base-box">
          <div class="config-title"><i class="el-icon-vertical-bar"></i>返回字段配置</div>
          <div class="config-contents">
            <avue-crud
              :defaults.sync="returnFieldsDefaults"
              :data="returnFields"
              :option="returnFieldsOption"
              @row-click="conditionsRowClick"
              @row-save="returnFieldsRowSave"
              @row-update="returnFieldsAddUpdate"
              @row-del="returnFieldsRowDel"
            >
              <template slot-scope="scope" slot="menuLeft">
                <el-button type="primary" icon="el-icon-plus" size="small" @click="addFields('returnFields')">添加字段</el-button>
              </template>
            </avue-crud>
          </div>
        </div>
      </div>

      <div class="designer-btns">
        <el-button type="primary" size="small" icon="el-icon-back" @click="onReturn"> 返回 </el-button>
        <el-button type="primary" size="small" icon="el-icon-document" @click="saveQueryConfigData"> 保存 </el-button>
      </div>
    </el-card>
    <common-modal-template ref="commonModalTemplate" :key="timer" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"></common-modal-template>
  </div>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { addOrUpdateApi, getApiInfo } from '@/api/quality/examine-searchflow-config';
export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      //初始数据加载书写
      apiInfo: {}, //基础信息
      apiInfoOption: {
        //基础信息内容配置
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '80',
        column: [
          {
            label: 'API名称',
            prop: 'name',
            span: 24,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          },
          {
            label: 'API编码',
            prop: 'code',
            span: 24,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          },
          {
            label: 'API地址',
            prop: 'url',
            span: 24,
            value: '/api/mes-product/apaas/api/command/query/execute',
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          },
          {
            label: 'SQL配置',
            prop: 'configSql',
            type: 'textarea',
            minRows: 10,
            maxRows: 10,
            span: 24
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 10,
            maxRows: 10,
            span: 24
          }
        ]
      },
      apiFlowId: '',
      paramsData: [], //参数信息配置数据
      paramsOption: {
        height: 630,
        border: true, //是否显示表格框线
        stripe: true, //是否显示条纹
        showHeader: true, //是否显示表头
        index: true, //是否显示表格序号
        indexLabel: '序号',
        addBtn: false, //新增按钮是否显示
        editBtn: false, //行编辑按钮是否显示
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false,
        filterBtn: false, //表格列过滤按钮是否显示
        selection: false,
        menuWidth: 100,
        column: [
          {
            label: '字段',
            prop: 'code'
          },
          {
            label: '字段注释',
            prop: 'value'
          }
        ]
      }, //参数信息配置表格配置属性
      conditions: [], //表条件
      conditionsRowIndex: 0, //条件信息行下标
      returnFieldsDefaults: {},
      returnFields: [], //表返回字段信息
      returnFieldsOption: {
        height: 630,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        viewBtn: false,
        addRowBtn: false,
        cellBtn: true,
        menuWidth: 150,
        column: [
          {
            label: '字段名称',
            prop: 'field',
            width: 200,
            cell: true
          },
          {
            label: '字段别名',
            prop: 'fieldAlias',
            cell: true
          },
          {
            label: '字段注释',
            prop: 'fieldNotes',
            cell: true
          }
        ]
      },
      returnFieldsIndex: 0,
      tableOption: {}, //公用模态框表格属性
      modalName: '',
      timer: new Date().getTime()
    };
  },
  created() {
    if (this.$route.query.apiId) {
      this.apiFlowId = this.$route.query.apiId;
      this.getModelFlowInfo(this.apiFlowId);
    }
  },
  methods: {
    getModelFlowInfo(apiId) {
      if (apiId) {
        getApiInfo(apiId).then((res) => {
          if (res.data) {
            this.apiInfo = res.data.data;

            let paramsData = this._get(this.apiInfo, 'paramsJson', '');
            this.paramsData = JSON.parse(paramsData || '[]');

            let returnFieldJson = this._get(this.apiInfo, 'returnFieldJson', '');
            this.returnFields = JSON.parse(returnFieldJson || '[]');
          } else {
            this.apiInfo = {};
          }
        });
      } else {
        this.apiInfo = {};
      }
    },
    /**
     * 打开常用参数模态框
     */
    openCommonParamsModal() {
      this.modalName = 'paramsModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择常用参数（请点击复选框进行多选）',
        url: '/api/blade-system/dict/dictionary?code=QMS_APAAS_SEARCH_PARAMS',
        isPage: false,
        rowSelectionType: 'multiple',
        searchLabelWidth: 50,
        selectable: (row, index) => {
          return !this.paramsData.map((item) => item.code).includes(row['dictKey']);
        },
        columnDefs: [
          {
            label: '参数',
            prop: 'dictKey',
            search: true
          },
          {
            label: '注释',
            prop: 'dictValue',
            search: true
          },
          {
            label: '序号',
            prop: 'sort'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    /**
     * 参数信息配置删除表格数据
     */
    paramsRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.paramsData.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
    },
    /**
     * 返回字段配置数据保存
     */
    returnFieldsRowSave(form, done) {
      this.$message.success('返回字段配置保存成功！');
      done();
    },

    /**
     * 返回字段配置数据编辑
     */
    returnFieldsAddUpdate(form, index, done) {
      this.$message.success('返回字段配置编辑成功！');
      done();
    },

    /**
     * 返回字段配置数据删除
     */
    returnFieldsRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.returnFields.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
    },
    /**
     * 表字段信息行点击
     */
    conditionsRowClick(row) {
      this.conditionsRowIndex = row.$index;
    },
    /**
     * 模态框表格选中数据返回
     */
    getSelectedRows(data) {
      if (this.modalName === 'paramsModal') {
        let selectedData = this._map(data, (item) => {
          return {
            code: item.dictKey,
            value: item.dictValue
          };
        });
        let paramMapData = [];
        this._forEach(this.paramsData, (item) => {
          paramMapData.push(item);
        });
        paramMapData.push(...selectedData);

        let hash = {}; //去重
        paramMapData = paramMapData.reduce((preVal, curVal) => {
          hash[curVal.code] ? '' : (hash[curVal.code] = true && preVal.push(curVal));
          return preVal;
        }, []);
        this.paramsData = paramMapData;
      }
      this.$refs.commonModalTemplate.hideModal();
    },

    /**
     * 保存查询API配置
     */
    saveQueryConfigData() {
      console.log(this.$refs.apiForm);
      if (!this.apiInfo.name) {
        this.$confirm('请输入API名称！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        return;
      }
      if (!this.apiInfo.code) {
        this.$confirm('请输入API编码！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        return;
      }
      if (!this.apiInfo.url) {
        this.$confirm('请输入API地址！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        return;
      }

      let paramMap = {
        id: this.apiFlowId,
        name: this.apiInfo.name,
        code: this.apiInfo.code,
        url: this.apiInfo.url,
        httpMethod: 'post',
        options: '',
        remark: this.apiInfo.remark,
        paramsJson: JSON.stringify(this.paramsData),
        configSql: JSON.stringify(this.apiInfo.configSql),
        returnFieldJson: JSON.stringify(this.returnFields)
      };

      if (this.apiFlowId) {
        this.apiInfo.paramsJson = JSON.stringify(this.paramsData);
        this.apiInfo.returnFieldJson = JSON.stringify(this.returnFields);
        addOrUpdateApi(this.apiInfo).then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.getModelFlowInfo(this.apiFlowId);
        });
      } else {
        addOrUpdateApi(paramMap).then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          let apiFlowId = this._get(res, 'data.data.id', '');
          this.$router.replace({ path: '/quality/inspectionReportConfig/examine-searchflow-config/edit', query: { apiId: apiFlowId } });
        });
      }
    },
    addFields(type) {
      this.returnFields.push({
        field: '',
        fieldNotes: '',
        fieldAlias: '',
        $cellEdit: true
      });
      switch (type) {
        case 'returnFields':
          let field = this.findObject(this.returnFieldsOption.column, 'field');
          let fieldNotes = this.findObject(this.returnFieldsOption.column, 'fieldNotes');
          field.cell = true;
          fieldNotes.cell = true;
          break;
        default:
          break;
      }
    },
    onReturn() {
      this.$router.replace('/quality/inspectionReportConfig/examine-api-flow-config');
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style scoped lang="scss">
.apaasApiConfigPage {
  padding: 0 6px;
  .baseInfoArea {
    display: flex;
    justify-content: space-between;
    .config-base-box {
      width: 39%;
      &.base {
        width: 29%;
      }
    }
  }
  .config-title {
    margin-bottom: 5px;
    padding-bottom: 5px;
    font-size: 16px;
    color: #02668a;
    font-weight: 600;
    border-bottom: 1px solid #c0c0c0;
  }
  .designer-btns {
    display: flex;
    justify-content: flex-end;
    margin-top: 5px;
  }
}
</style>
